<template>
  <div class="app">
    <Left :list="list" @keyDown="keyDown" :power="power"/>
    <Controller 
    :id="curId"
    :power.sync="power"
    :bank.sync="bank"
    @changeVolume="changeVolume"
    />
    <audio ref="audioRef" :src="audioUrl"></audio>
  </div>
</template>

<script>
import axios from 'axios';
import Left from './components/Left.vue';
import Controller from './components/Controller.vue'
export default {
    data() {
        return {
            list:[],
            audioUrl:'',
            curId:'',
            power:true,
            bank:false
        }
    },
    created() {
        this.getList()
    },
    methods:{
        async getList(){
            const res = await axios.get('https://zyxcl.xyz/exam_api/music/list')
            this.list = res.data.value
        },
        // 传参 给item对象加个新属性
        keyDown({id,checked}) {
            const item = this.list.find(v=>v.id === id)
            this.$set(item,'checked',checked)
            // 判断 每一项是否被选中并且开关是否开启  一项为假不播放音频  
            if(item.checked && this.power) {
                // console.log(item)
                this.curId=id
                // 先赋值给url
                this.audioUrl = this.bank? item.bankUrl : item.url

                this.$nextTick(() => {
                    // 等组件渲染完成执行此条函数
                    // this.$refs.audioRef.load()
                    this.$refs.audioRef.play()
                })

            }          
        },
        // 给音频设置音量
        changeVolume(value) {
            this.$refs.audioRef.volume = value 
        }
    },
    watch: {
        power() {
            if(!this.power) {
                this.curId = ''
            }
        }
    },
    components:{
        Left,
        Controller
    }
}
</script>

<style lang="scss">
body{
    background: #989898;
}
.app{
    width: 800px;
    margin: 0 auto;
    border: 3px solid #f2b03e;
    background: #b1b1b1;
    display: flex;

}
</style>
